<template>
  <div class="MultipleChoiceSearch">
    <input v-model="keyWord" type="text" placeholder="支持模糊搜索" />
    <ul class="selectUl">
      <li
        v-for="(item, index) in getData"
        :key="index"
        @click="select(item, index)"
        :class="{ active: item.active }"
        :title="item.value"
      >
        {{ item.value }}
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  name: "MultipleChoiceSearch",
  props: ["data"],
  data() {
    return {
      // 搜索关键词
      keyWord: "",
    };
  },
  computed: {
    // 根据关键词过滤数据
    getData() {
      if (!this.data) {
        return [];
      }
      return this.data.filter((item) => item.value.indexOf(this.keyWord) > -1);
    },
  },
  methods: {
    // 选中
    select(item, index) {
      if (item.active) {
        //为item添加不存在的属性，需要使用vue提供的
        //Vue.set( object, key, value )方法。
        this.$set(item, "active", false);
      } else {
        this.$set(item, "active", true);
      }
      // 返回选中的数组
      console.log(
        this.data.filter((item) => {
          return item.active;
        })
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.MultipleChoiceSearch {
  > input {
    width: 100%;
    height: 32px;
    border: 1px solid #cbcbcb;
    border-radius: 4px;
    padding: 0 12px;
    font-size: 14px;
    font-weight: 500;
    color: #999999;
    line-height: 32px;
  }
  > ul.selectUl {
    width: 260px;
    height: 264px;
    background: #ffffff;
    border: 1px solid #cbcbcb;
    border-radius: 4px;
    overflow-y: scroll;
    > li {
      width: 100%;
      font-size: 14px;
      font-weight: 500;
      color: #333333;
      line-height: 32px;
      padding-left: 12px;
      margin-bottom: 1px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      &.active {
        background: #4475f6;
        color: #ffffff;
      }
    }
  }
}
</style>